package com.prizedraw.prize_draw.security;

import cn.hutool.json.JSONUtil;
import com.prizedraw.prize_draw.common.lang.Result;
import com.prizedraw.prize_draw.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        //生成jwt，并放置到请求头中
        String jwt = jwtUtil.generateToken(((AccountUser)authentication.getPrincipal()).getUserId());
        log.info("生成JWT成功！username---{}，userID---{}，JWT---{}",authentication.getName(),((AccountUser)authentication.getPrincipal()).getUserId(),jwt);
        httpServletResponse.setHeader(jwtUtil.getHeader(), jwt);
        Result result = Result.succ("");
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
